<template>
  <el-dialog v-model="visible" :title="title" width="600px">
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>

      <el-form-item label="角色编码" prop="code">
        <el-input v-model="formData.code" />
      </el-form-item>

      <el-form-item label="描述信息" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="3" />
      </el-form-item>

      <el-form-item label="排序" prop="order_num">
        <el-input-number v-model="formData.order_num" />
      </el-form-item>

      <el-form-item label="状态">
        <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
      </el-form-item>

      <!-- 分配菜单 -->
      <el-form-item label="分配菜单">
        <el-select v-model="formData.menu_ids" multiple placeholder="请选择菜单">
          <el-option
            v-for="item in allMenuOptions"
            :key="item.id"
            :label="renderLabelWithIndent(item, item.level)"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 分配权限 -->
      <el-form-item label="分配权限">
        <el-select v-model="formData.permission_ids" multiple placeholder="请选择权限">
          <el-option
            v-for="item in allPermissionOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { funPick } from '@/utils/common'
import { useMenuStore } from '@/stores/menuStore'
import { usePermissionStore } from '@/stores/permissionStore'

const menuStore = useMenuStore()
const permissionStore = usePermissionStore()

// ====================
// 响应式数据与 Props/Emits
// ====================
const props = defineProps({
  modelValue: Boolean,
  formData: Object
})

const emit = defineEmits(['update:modelValue', 'submit'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const title = computed(() => (formData.value.id ? '编辑角色' : '新增角色'))

const formRef = ref(null)
const formData = ref({
  name: '',
  code: '',
  description: '',
  order_num: 0,
  status: 1,
  id: null
})

// ====================
// 表单初始化逻辑
// ====================
// 递归渲染带缩进的菜单标签
const renderLabelWithIndent = (menu, level = 0) => {
  const indent = '---'.repeat(level)
  return `${indent}${menu.name}`
}

// 使用 store 中带层级信息的菜单列表
const allMenuOptions = computed(() => menuStore.flatMenuListWithLevel)

// 获取所有权限选项
const allPermissionOptions = computed(() => permissionStore.allPermissions)

// 初始化表单数据
watch(
  () => props.formData,
  (val) => {
    formData.value = val
      ? funPick(val, ['id', 'name', 'code', 'description', 'order_num', 'status', 'menu_ids', 'permission_ids'])
      : {
          name: '',
          code: '',
          description: '',
          order_num: 0,
          status: 1,
          menu_ids: [],
          permission_ids: [],
          id: null
        }
  },
  { immediate: true }
)

// ====================
// 表单验证与提交
// ====================
// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  order_num: [{ type: 'number', message: '排序必须为数字', trigger: 'blur' }]
}

// 表单提交触发方法
const handleSubmit = async () => {
  try {
    await formRef.value.validate() // 恢复表单验证
    emit('submit', formData.value) // 通知父组件处理提交逻辑
    visible.value = false   // 关闭弹窗
  } catch (error) {
    ElMessage.error('请填写完整的表单信息')
  }
}
</script>

<style scoped>
/* 可以复用 MenuForm.vue 中的样式 */
</style>